package com.ts.api.module.api.service.impl;

import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.constant.api.ApiEnum;
import com.ts.api.common.constant.api.ApiVersionModeEnum;
import com.ts.api.exp.ApiMsgException;
import com.ts.api.module.api.convert.receive.entity.ApiReceivePhoneMd5DataExchange;
import com.ts.api.module.api.convert.receive.handler.DelegatingApiReceiveExistHandler;
import com.ts.api.module.api.entity.ApiUserRequest;
import com.ts.api.module.api.entity.bo.ApiCheckHistoryUserBO;
import com.ts.api.module.api.entity.po.ApiKeyPO;
import com.ts.api.module.api.entity.vo.ReqApiParameterVO;
import com.ts.api.module.api.handler.ApiReceiveHandler;
import com.ts.api.module.api.service.ApiBizRequiredService;
import com.ts.api.module.api.service.ApiReceivePreMd5Service;
import com.ts.api.module.channel.service.ChannelUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class ApiReceivePreMd5ServiceImpl implements ApiReceivePreMd5Service {

    @Autowired
    private ApiReceiveHandler apiReceiveHandler;
    @Autowired
    private ApiBizRequiredService apiBizRequiredService;
    @Autowired
    private ChannelUserService channelUserService;
    @Autowired
    private DelegatingApiReceiveExistHandler delegatingApiReceiveExistHandler;

    @Override
    public Map<String, Object> dataExchange(ApiKeyPO apiKeyPO, RequestVO requestVO) {
        try {
            //  1.构建撞库请求对象
            ReqApiParameterVO reqApiParameterVO = apiReceiveHandler.handlePreDataExchangeMd5Request(apiKeyPO, requestVO);

            //  验证版本
            if (!ApiVersionModeEnum.MD5.hasVersionMode(apiKeyPO.getApiVersionMode())) {
                throw new ApiMsgException(ApiEnum.API_VERSION_MODE_ERROR);
            }

            //  2.获取参数
            ApiUserRequest apiUserRequest = reqApiParameterVO.getApiUserRequest();
            String phoneMd5 = apiUserRequest.getPhoneMd5();

            //  3.检验逻辑
            ApiCheckHistoryUserBO channelCheckHistoryBO = ApiCheckHistoryUserBO.createApiKeyByMd5(apiKeyPO, phoneMd5);
            boolean existHistory = apiBizRequiredService.existHistoryUser(channelCheckHistoryBO);
            boolean existLocal = channelUserService.hasLocalExist(phoneMd5);

            //  4.返回失败
            if (existHistory || existLocal) {
                return delegatingApiReceiveExistHandler.respDataExchange(ApiReceivePhoneMd5DataExchange.fail("已存在", 1000));
            }
            //  4.返回成功
            return delegatingApiReceiveExistHandler.respDataExchange(ApiReceivePhoneMd5DataExchange.suc());
        } catch (Exception e) {
            throw apiReceiveHandler.dataExchangePreWrapApiException(e);
        }
    }
}
